<template>
  <div class="pupop-map-chose">
    <div class="loading"></div>
    <div class="madel-mark" @click="closePupop()"></div>
    <div v-show="show" class="content">
      <input id='seachAddress' v-model="searchName" placeholder="位置模糊查询" class="input-with-select" />
      <div id="containers" class="delivery-map"></div>
      <div class="header flex-row">
        <div class="left flex-row" v-if="province">
          <div class="title">当前位置：</div>
          <div class="text"><el-input type="text" style="min-width: 500px;" v-model="province" /></div>
        </div>
        <div class="left" v-else>
          <div class="title">请点击地图确认商家位置</div>
        </div>
        <el-button type="primary" size="mini" @click="chosePos()">确认位置</el-button>
      </div>

    </div>
  </div>
</template>
<script>
  import AMap from 'AMap'
  export default {
    data() {
      return {
        show: false,
        map: null,
        searchName: '', // 搜索区域
        province: '',
        shopMarker: null,
        polygon1: null, // 围栏
        distrange: null,
        lat: null,
        lng: null,
        searchMakrer: null
      }
    },
    methods: {
      removeChildDom() { // 删除页面
        // 如果已经存在，则删除原来的
        const node = document.querySelector('.pupop-map-chose')
        if (node && node.parentNode) {
          node.parentNode.removeChild(node)
        }
        const nodeMap = document.querySelector('.amap-sug-result')
        if (nodeMap && nodeMap.parentNode) {
          nodeMap.parentNode.removeChild(nodeMap)
        }
      },
      init() { //初始化地图
        this.map = new AMap.Map('containers', {
          center: [116.481181, 39.989792],
          resizeEnable: true,
          zoom: 16
        })
        this.map.on('click', this.showInfoClick)
        const _this = this
        AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function () {
          _this.map.addControl(new AMap.ToolBar())
          _this.map.addControl(new AMap.Scale())
        })
        AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'], function(){
          var autoOptions = { input: "seachAddress" }
          var autocomplete= new AMap.Autocomplete(autoOptions)
          AMap.event.addListener(autocomplete, "select", function(e){
            const pos = [e.poi.location.O,e.poi.location.P]
             if ( _this.searchMakrer) _this.map.remove(_this.searchMakrer)
             _this.searchMakrer = new AMap.Marker({
              map: _this.map,
              position: pos
            })
            _this.map.setCenter(pos)
          })
        })
        if (this.distrange) {
          this.showRectangleMax(this.distrange)
        }
        if (this.lat && this.lng) {
          this.tagBusinessLocation([this.lng, this.lat])
        }
      },
      showInfoClick(e) { // 点击事件
        this.$confirm('是否确认当前位置为您的门店位置？', '选址提示！').then(() => {
          if (this.distrange) {
            if (this.inPolygon([e.lnglat.getLng(), e.lnglat.getLat()], this.map.getAllOverlays('polygon')[0])) {
              this.surePos(e)
            } else {
              this.$message.error('此位置不在网格内！')
            }
          } else {
            this.surePos(e)
          }
        })
      },
      surePos(e) { // 点击返回地址和经纬度
        var geocoder = new AMap.Geocoder()
        geocoder.getAddress(e.lnglat.getLng()+','+ e.lnglat.getLat(), (status, result) => {
          if (status === 'complete'&& result.regeocode) {
            this.province = result.regeocode.formattedAddress
            this.lng = e.lnglat.getLng()
            this.lat = e.lnglat.getLat()
            this.tagBusinessLocation([this.lng, this.lat])
          }else{alert(JSON.stringify(result))}
        })
      },
      tagBusinessLocation(pos) { // 标记商家位置
        if (this.shopMarker) this.map.remove(this.shopMarker)
        this.shopMarker = new AMap.Marker({
          map: this.map,
          icon: "assets/img/poi-marker-red.png",
          position: pos,
          offset: new AMap.Pixel(-23, -63)
        })
        this.map.setCenter(pos)
      },
      chosePos() { // 确认所选位置
        if (this.lat && this.lng) {
          this.callback({ // 本组件返回给外部调用
            province: this.province,
            lat: this.lat,
            lng: this.lng
          })
          this.show = false
          this.removeChildDom()
        } else {
          this.$alert('请点击地图选址位置')
          return false
        }
      },
      showRectangleMax(pos) { //显示代理商区域
        let position = pos.trim()
        let lastStr = position.charAt(position.length - 1)
        if (lastStr == '|') {
          position = position.substring(0, position.lastIndexOf('|'))
        }
        let positionArr = []
        position.split('|').forEach(item => {
          positionArr.push(item.split(','))
        })
        if (this.polygon1) map.remove(this.polygon1)
        this.polygon1 = new AMap.Polygon({
          map: this.map,
          path: positionArr,
          strokeColor: "#ff232f",
          strokeOpacity: 1,
          strokeWeight: 2,
          fillColor: "#6bf517",
          fillOpacity: 0.35
        })
        this.polygon1.on('click', this.showInfoClick)
        this.$nextTick(() => {
          this.map.setFitView()
        })
      },
      inPolygon(inPos, polygon) { //验证多边形是否在围栏内部
        const marker1InPolygon = polygon.contains(inPos)
        return marker1InPolygon
      },
      closePupop() { // 点击蒙城关闭
        this.removeChildDom()
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.init()
      })
    },
    beforeMount() { // 防止进入前又数据
      this.removeChildDom()
    }
  }
</script>
<style lang="scss">
  .amap-sug-result{
    position: fixed;
    z-index: 1000;
  }
  #seachAddress {
    position: absolute !important;
    top: 10px !important;
    left: 50% !important;
    z-index: 1;
    transform: translate(-50%, 0);
    background-color: #fff;
    font-size: 15px;
    font-weight: 300;
    height: 20px;
    line-height: 20px;
    padding: 5px;
    text-overflow: ellipsis;
    width: 400px;
  }
  #seachAddress:focus {
    border-color: #4d90fe;
  }
</style>
<style lang="scss" scoped>
  .madel-mark{
    background: rgba(0,0,0,.3);
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    top: 0;
    z-index: 999;
    .center{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .content{
    position: absolute;
    bottom: 0;
    right: 0;
    z-index: 1000;
    width: 85%;
    height: 80%;
    min-height: 600px;
    background: #fff;
    .header{
      height: 49px;
      padding: 0 10px;
      justify-content: space-between;
      border-bottom: 1px solid #ccc;
      .left{
        flex: 1;
        display: flex;
        .title{
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
    #containers{
      width: 100%;
      height: calc(100% - 50px);
    }
  }
</style>
